﻿using System;
using System.Runtime.InteropServices;
namespace WPFExcelReport
{

    public struct COPYDATASTRUCT
    {
        public IntPtr dwData;
        public IntPtr cbData;
        public IntPtr lpData;
    }
    /*    public struct COPYDATASTRUCT
     {
         public int dwData;
         public int cbData;
         [MarshalAs(UnmanagedType.LPStr)]
         public string lpData;
     }*/

    public class IF2ITX
    {
        public IF2ITX()
        {
        }
        public IF2ITX(long hwnd, string inf)
        {
            WINDOW_HANDLER = hwnd;
            IFQI = inf;
        }
        public const long WM_COPYDATA = 0x004A;
        //[DllImport("User32.dll")]
        //public static extern IntPtr SendMessageA(long hwnd, long wMsg, long wParam, ref COPYDATASTRUCT lParam);

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessage(IntPtr handle, int messg, int wparam, ref COPYDATASTRUCT lParam);

        public string hwndQI = "", IFQI = "";
        long WINDOW_HANDLER;          // 存放实例1中的WB14IT窗口的窗口句柄    
        public IntPtr SEND2QI(double MTR)
        {
            IntPtr rtnmsg;
            int idx = 0;
            string msg = "";
            MTR = Helpers.Helper.RoundX(Convert.ToDouble(MTR), 100);
            idx = MTR.ToString().IndexOf(".");
            string lqty = "";
            string rqty = "";
             if (idx < 0)
            {
                lqty = MTR.ToString();
                rqty = "00";
            }
            else
            {
                lqty = MTR.ToString().Substring(0, idx);
                rqty = Helpers.Helper.Left(MTR.ToString().Substring(idx + 1) + "00", 2);
            }
             msg = IFQI + "X" + "BRUTLG.QI03=" + lqty + "," + rqty  +"        ";//最后一个字节与空格在一起可能乱码
             byte[] sarr = System.Text.Encoding.ASCII.GetBytes(msg);//System.Text.Encoding.Default.GetBytes(msg);
            int len = sarr.Length;
            COPYDATASTRUCT cdata;

            cdata.dwData = (IntPtr)3;
            cdata.cbData = (IntPtr)(len + 1);
            cdata.lpData = Marshal.AllocHGlobal(sarr.Length);
            Marshal.Copy(sarr, 0, cdata.lpData, sarr.Length);
            /*
           cdata.dwData = 3;
           cdata.lpData = msg;
           cdata.cbData = len + 1;*/
            rtnmsg = SendMessage((IntPtr)WINDOW_HANDLER, (int)WM_COPYDATA, (int)0, ref cdata);
            Marshal.FreeHGlobal(cdata.lpData);
            return rtnmsg;
        }
    }

}
